let _Vue = null;
export default class VueRouter {
    static install(Vue){
        if(VueRouter.install.installed){
            return;
        }
        VueRouter.install.installed = true;
        _Vue = Vue;

        Vue.mixin({
            beforeCreate() {
                if(this.$options.router){
                    _Vue.prototype.$router = this.$options.router;
                    this.$options.router.init();
                }
            }
        })
    }
    constructor(options){
        this.options = options;
        this.routeMap = {};
        this.data = _Vue.observable({
            current: '/'
        });
        // this.init();
    }
    init(){
        this.initRouteMap();
        this.initComponent(_Vue);
        this.initEvent();
    }
    initRouteMap(){
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component;
        })
    }
    initComponent(Vue){
        const _this = this;
        Vue.component('router-link',{
            props: ['to'],
            methods: {
                clickHandler(e){
                    e.preventDefault();
                    location.hash = this.to;
                    _this.data.current = this.to;
                }
            },
            render(h) {
                return h('a',{
                    attrs: {
                        href: '#' + this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                },this.$slots.default)
            }
        });
        Vue.component('router-view', {
            render(h){
                return h(_this.routeMap[_this.data.current]);
            }
        })
    }
    initEvent(){
        window.addEventListener('hashchange',() => {
            this.data.current = location.hash.replace('#','');
        })
    }
}
